<template>
  <div>
    <n-layout has-sider style="height: 100%;max-height:85vh">
      <n-layout-sider :native-scrollbar="true" bordered collapse-mode="width" :collapsed-width="10" :width="340"
        :collapsed="collapsed" :show-trigger="true" @collapse="collapsed = true" @expand="collapsed = false">
        <n-card segmented style="height:100%;" header-style="padding:10px;" content-style="padding:0px;overflow: auto;"
          footer-style="padding:10px">
          <template #header>
            <n-input-group>
              <n-input placeholder="输入关键词进行过滤" v-model:value="searchFormType.name" clearable
                @keyup.enter="getTypeList" />
              <n-button type="primary" @click="getTypeList">
                搜索
              </n-button>
            </n-input-group>

          </template>
          <n-menu :collapsed="collapsed" :indent="18" :options="menuOptions" @update:value="handleUpdateValue"
            :node-props="buildNodeProps" />
          <template #footer position="absolute">
            <n-button type="primary" style="width: 100%;" @click="handleAddType">
              <template #icon>
                <icon-ri:add-circle-fill></icon-ri:add-circle-fill>
              </template>
              字典分类
            </n-button>
          </template>
        </n-card>
      </n-layout-sider>

      <n-layout-content>
        <n-card class="right-card" segmented style="height: 100%">
          <template #header>
            <n-button strong secondary style="margin-right: 10px;" type="info" @click="handleAddClick">
              <template #icon>
                <Icon icon="ion:add-sharp"></Icon>
              </template>
            </n-button>
            <popconfirm-btn :disabled="!(checkRows && checkRows.length > 0)" btnStr="" confirmText="是否确定删除" secondary
              type="error" icon="ri-delete-bin-2-line" :local-icon="true"
              :on-positive-click="handleDeleteListPositive" />
          </template>

          <n-data-table :columns="columns" :data="list" :loading="loading" :empty="empty" :bordered="false"
            :row-key="(row: SysDictData) => row.id!" @update:checked-row-keys="handleCheck" />
        </n-card>
      </n-layout-content>

    </n-layout>

    <n-modal v-model:show="showModal" title="字典值" display-directive="if" :bordered="false" preset="card" class="w-600px"
      size="huge" :closable="false">
      <slef-form :formData="formData" @close="handleCloseModal" @list="getList"></slef-form>
    </n-modal>

    <n-modal v-model:show="showTypeModal" title="字典分类" display-directive="if" :bordered="false" preset="card"
      class="w-600px" size="huge" :closable="false">
      <type-form :formData="typeFormData" @close="handleCloseTypeModal" @list="getTypeList"></type-form>
    </n-modal>
  </div>
</template>

<script setup lang='tsx'>
import { ref, onMounted, reactive } from 'vue';
import { DataTableColumn, NSpace, NEllipsis } from 'naive-ui';
import { useLoading } from '@/hooks';
import { fetchDataListByType, fetchData, fetchDelData } from '@/service/api/sys/dict/data'
import { fetchTypeList, fetchDelType, fetchType } from '@/service/api/sys/dict/type'
import TooltipBtn from "~/src/components/custom/tooltip-btn.vue"
import TablePopconfirmBtn from "~/src/components/custom/table-popconfirm-btn.vue"
import SMoreTableBtn from "~/src/components/custom/s-more-table-btn.vue"
import PopconfirmBtn from "~/src/components/custom/popconfirm-btn.vue"
import slefForm from "./dict-data/form.vue"
import TypeForm from "./dict-type/form.vue"
import { Icon } from '@iconify/vue';
import type { MenuOption } from 'naive-ui'
import { SysDictData } from "./dict-data/index"
import { SysDictType } from "./dict-type/index"
let collapsed = ref(false);
let curKey = ref();
const menuOptions = ref<MenuOption[]>([])
interface DictType extends SysDictType { }

const columns: DataTableColumn<SysDictData>[] = [
  {
    type: "selection"
  },

  {
    title: '字典标签',
    key: 'label',
    align: 'center',
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: '字典键值',
    key: 'value',
    align: 'center',
    ellipsis: {
      tooltip: true
    }
  },
  {
    title: "操作列",
    key: "edit",
    align: 'center',
    width: 200,
    fixed: 'right',
    render(rowData: SysDictData) {
      return <>
        <NSpace justify="center">
          <TooltipBtn str="编辑" type="success" onClick={() => handleEditClick(rowData)} />
          <TablePopconfirmBtn confirmText="是否确认删除当前内容" onPositiveClick={() => handleDeletePositive(rowData)} />
        </NSpace>
      </>
    }
  }
];

const searchForm = reactive<SysDictData>({});
const searchFormType = reactive<SysDictType>({ name: '' });
const list = ref<SysDictData[]>([]);
const checkRows = ref<SysDictData[]>([]);
const { loading, startLoading, endLoading, empty, setEmpty } = useLoading();

const showModal = ref(false);
const showTypeModal = ref(false);
const formData = ref<SysDictData>(initFormData())
const typeFormData = ref<DictType>(initTypeFormData())
async function getList() {
  checkRows.value = []
  startLoading()
  const { data } = await fetchDataListByType(searchForm.type!)
  list.value = data || []
  setEmpty(!list.value.length)
  endLoading()
}

function initFormData(): SysDictData {
  return {}
}
function initTypeFormData(): DictType {
  return {}
}
function buildNodeProps() {
  return {
    class: "sys-menu-tree-node"
  }
}
function handleCheck(keys: Array<string | number>, rows: SysDictData[]) {
  checkRows.value = rows.filter(it => it != undefined)
}

async function handleDeleteListPositive() {
  await fetchDelData(checkRows?.value.map(it => it.id!))
  getList()
  return true;
}
async function handleDeletePositive(row: SysDictData): Promise<boolean> {
  if (!row || !row.id) {
    window.$message?.error("数据id异常,请刷新后重试")
    return false
  }
  await fetchDelData([row.id])
  getList()
  return true
}

async function handleEditClick(row: SysDictData) {
  if (!row || !row.id) {
    window.$message?.error("当前行数据异常,请刷新后重试")
    return;
  }
  const { data } = await fetchData(row.id)
  formData.value = data!;
  showModal.value = true;
}
function handleAddType() {
  typeFormData.value = initTypeFormData();
  showTypeModal.value = true
}
async function handleEditType(row: DictType) {
  const { data } = await fetchType(row.id!)
  typeFormData.value = data!;
  showTypeModal.value = true
}
async function handleDeleteType(id: any) {
  if (!id) {
    window.$message?.error("数据id异常,请刷新后重试")
    return false
  }
  await fetchDelType([id])
  getTypeList()
  return true
}
function handleAddClick() {
  formData.value = initFormData();
  if (!curKey.value) {
    window.$message?.error("选择字典分类后才可添加字典值")
    return
  }
  formData.value.type = curKey.value
  showModal.value = true;
}
function handleCloseModal() {
  formData.value = initFormData();
  showModal.value = false;
}
function handleCloseTypeModal() {
  typeFormData.value = initTypeFormData();
  showTypeModal.value = false
}

function handleUpdateValue(key: string, item: MenuOption) {
  searchForm.type = String(item.key)
  curKey.value = String(item.key)
  getList()
}
async function getTypeList() {
  const { data } = await fetchTypeList(searchFormType);
  let list = data || []
  menuOptions.value = []

  list.forEach(it => {
    //@ts-ignore
    menuOptions.value.push({
      key: it.type,
      label: () => {
        return <>
          <NSpace style="flex-flow: row;text-align: end" justify="space-between" class="suffix" size={5}>
            <NEllipsis style="text-align:center;margin-top:.2rem">{it.name}</NEllipsis>
            <NEllipsis style="text-align:center;margin-top:.2rem">{it.type}</NEllipsis>
            <SMoreTableBtn class="suffix-more" itemStyle="width:5%">
              <TooltipBtn str="编辑" style="margin-right:.5rem" type="success" onClick={() => handleEditType(it)} />
              <TablePopconfirmBtn confirmText="是否确认删除当前内容" onPositiveClick={() => handleDeleteType(it.id)} />
            </SMoreTableBtn>
          </NSpace>
        </>
      }
    } as MenuOption)
  })
}


onMounted(() => {
  getTypeList();
})
</script>

<style lang='scss' scoped>
:deep(.sys-menu-tree-node) {
  .suffix-more {
    visibility: hidden;
    background-color: transparent;
  }

  &:hover .suffix-more {
    visibility: visible;
  }
}
</style>
